
import { Component } from "react";

// https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

export default class CartItem extends Component {
    state = {
        item: {
            id: 9527 , name: 'Huawei P50E' , price: 4999 , number: 2
        }
    }
    constructor(props){
        super(props);
        console.log( 'CartItem constructor' );
    }
    static getDerivedStateFromProps( props , state ) {
        console.log( 'CartItem.getDerivedStateFromProps' );
        console.log( '\tprops: ' , props , ' , state: ' , state );
        return state ;
    }
    shouldComponentUpdate(nextProps, nextState){
        console.log( 'CartItem : shouldComponentUpdate' );
        console.log( '\tnextProps: ' , nextProps );
        console.log( '\tnextState: ' , nextState );
        return true ;   
    }
    render(){
        console.log( "CartItem : render" );
        let { id , name , price , number } = this.state.item ;
        return (
            <div className="item">
                <span>{id}</span>
                <span>{name}</span>
                <span>{price}</span>
                <span className="num">
                    <i onClick={this.handler}>-</i>
                    <b>{number}</b>
                    <i onClick={this.handler}>+</i>
                </span>
                <span>{price * number}</span>
            </div>
        );
    }
    componentDidUpdate(){
        console.log( "CartItem : componentDidUpdate" );
    }
    componentWillUnmount(){
        console.log( "CartItem : componentWillUnmount" );
    }
    handler = e => {
        console.log( e );
        let content = e.target.innerHTML;
        let op = content.trim();

        let x = {...this.state.item} ;

        if( op === '-' ) {
            x.number-- ; // x.number = x.number - 1 ;
            this.setState({
                item: x
            });
        }
        if( op === '+' ) {
            x.number++ ; // x.number = x.number + 1 ;
            this.setState({
                item: x
            });
        }
    }
}